package com.zentrale1.noodlemail;
import java.io.*;
import java.util.ArrayList;

/*
 * The MIT License
 * 
 * Copyright (c) 2010 Andreas Fleig
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 */


/**
 * reads and writes messages from/to Maildirs
 * @author afleig
 *
 */
public class Maildir 
{
	private String path;
	
	public Maildir(String path)
	{
		this.path = path;
	}

	/**
	 * Scans the Maildir for folders and returns them
	 * @return Array of Maildir objects of sub-folders
	 */
	public Maildir[] getFolders()
	{
		Maildir[] folders = null;
		ArrayList<Maildir> dirList = new ArrayList<Maildir>();
		File root = new File(this.path);
		if (root.exists() && root.isDirectory()) {
			File[] files = root.listFiles();
			for (File file : files) {
				if (file.isDirectory() 
						&& file.getName().substring(0, 1).equals(".")) {
					Maildir subDir = new Maildir(file.getAbsolutePath());
					dirList.add(subDir);
				}
			}
			folders = dirList.toArray(new Maildir[dirList.size()]);
			return folders;
		}
		return folders;
	}
	
	/**
	 * Lists all read or unread messages in a Maildir
	 * @param unread true, if only unread messages shall be returned, false for 
	 *  			 only read messages
	 * @return array of message file paths
	 */
	public String[] listMessages(boolean unread)
	{
		String[] messages = null;
		String subPath = unread ? "new" : "cur";
		String path = this.getPath() + "/" + subPath;
		File folder = new File(path);
		File[] files = folder.listFiles();
		ArrayList<String> messageList = new ArrayList<String>();
		
		for (File file : files) {
			if (file.isFile()) {
				messageList.add(file.getAbsolutePath());
			}
		}
		
		messages = messageList.toArray(new String[messageList.size()]);
		return messages;
	}
	
	
	
	public String getPath()
	{
		return this.path;
	}
	
	/**
	 * Returns the basename of the folder
	 * @return
	 */
	public String getName()
	{
		File f = new File(this.getPath());
		return f.getName();
	}
	
	
}
